package com.woniuxy.cloud.carl.store.app.apiImpl;


import cn.hutool.core.bean.BeanUtil;
import com.woniuxy.cloud.carl.store.client.StoreSaleClient;
import com.woniuxy.cloud.carl.store.client.result.StoreSaleDto;
import com.woniuxy.cloud.carl.store.client.result.StoreSaleRedisForm;
import com.woniuxy.cloud.carl.store.infra.model.Store;
import com.woniuxy.cloud.carl.store.infra.model.StoreSale;
import com.woniuxy.cloud.carl.store.service.StoreSaleService;
import com.woniuxy.cloud.carl.store.service.StoreService;
import com.woniuxy.result.Result;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 门店月销表 前端控制器
 * </p>
 *
 * @author Lucas
 * @since 2023-07-19
 */
@RestController
public class StoreSaleAPIImpl implements StoreSaleClient {
    @Autowired
    StoreSaleService storeSaleService;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    StoreService storeService;
    @Override
    public Result<List<StoreSaleDto>> getStoreSale(Long storeId) {
        return storeSaleService.getStoreSale(storeId);
    }

    @Override
    @Scheduled(cron = "0 0 0 1 * ?")
    public void getInfoFromRedis() {
        //需把所有的门店id存入redis中，这里用数据库代替
        List<Store> list = storeService.list();
        //从redis中拿出所有的门店id，然后根据门店id去查存在redis中的月销数据
        RMap<String, StoreSaleRedisForm> map = redissonClient.getMap("store_sale");
        Date date = new Date();
        date.setMonth(date.getMonth()-1);
        System.out.println(date);
        for (Store store : list) {
            StoreSaleRedisForm storeSaleRedisForm = map.get(store.getStoreId());
            StoreSale storeSale = BeanUtil.copyProperties(storeSaleRedisForm, StoreSale.class);
            storeSale.setTime(date);
            storeSale.setStoreId(store.getStoreId());
            storeSaleRedisForm.setAmount(new BigDecimal(0));
            storeSaleRedisForm.setOrderCount(0);
            map.put(store.getStoreId().toString(),storeSaleRedisForm);
            storeSaleService.save(storeSale);
        }
    }
}

